﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.GridPersons.Authorization;
using LeadThing.AbpZeroTemplate.GridPersons.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Areas;
using LeadThing.AbpZeroTemplate.PersonTypes;

namespace LeadThing.AbpZeroTemplate.GridPersons
{
    /// <summary>
    /// 网格基本信息服务实现
    /// </summary>
    [AbpAuthorize(GridPersonAppPermissions.GridPerson)]


    public class GridPersonAppService : AbpZeroTemplateAppServiceBase, IGridPersonAppService
    {
        private readonly IRepository<GridPerson, long> _gridPersonRepository;
        private readonly IGridPersonListExcelExporter _gridPersonListExcelExporter;
        private readonly IRepository<Area, long> _areaRepository;
        private readonly IRepository<PersonType, long> _personTypeRepository;


        private readonly GridPersonManage _gridPersonManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public GridPersonAppService(IRepository<GridPerson, long> gridPersonRepository,
GridPersonManage gridPersonManage
      , IGridPersonListExcelExporter gridPersonListExcelExporter, IRepository<Area, long> areaRepository, IRepository<PersonType, long> personTypeRepository
  )
        {
            _gridPersonRepository = gridPersonRepository;
            _gridPersonManage = gridPersonManage;
            _gridPersonListExcelExporter = gridPersonListExcelExporter;
            _areaRepository = areaRepository;
            _personTypeRepository = personTypeRepository;
        }


        #region 实体的自定义扩展方法
        private IQueryable<GridPerson> _gridPersonRepositoryAsNoTrack => _gridPersonRepository.GetAll().AsNoTracking();


        #endregion


        #region 网格基本信息管理

        /// <summary>
        /// 根据查询条件获取网格基本信息分页列表
        /// </summary>
        public async Task<PagedResultDto<GridPersonListDto>> GetPagedGridPersonsAsync(GetGridPersonInput input)
        {

            var query = _gridPersonRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.PersonName.Contains(input.Filter));

            //TODO:根据传入的参数添加过滤条件
            #region TODO:根据传入的参数添加过滤条件

            //人员姓名
            if (!string.IsNullOrWhiteSpace(input.PersonName))
                query = query.Where(p => p.PersonName.Contains(input.PersonName));
            //人员手机号
            if (!string.IsNullOrWhiteSpace(input.PersonPhone))
                query = query.Where(p => p.PersonPhone.Contains(input.PersonPhone));
            //身份证号
            if (!string.IsNullOrWhiteSpace(input.IDCard))
                query = query.Where(p => p.IDCard.Contains(input.IDCard));
            //网格员姓名
            if (!string.IsNullOrWhiteSpace(input.GridName))
                query = query.Where(p => p.GridName.Contains(input.GridName));
            //网格员手机号
            if (!string.IsNullOrWhiteSpace(input.GridPhone))
                query = query.Where(p => p.GridPhone.Contains(input.GridPhone));
            //协管员姓名
            if (!string.IsNullOrWhiteSpace(input.AssistName))
                query = query.Where(p => p.AssistName.Contains(input.AssistName));
            //协管员手机号
            if (!string.IsNullOrWhiteSpace(input.AssistPhone))
                query = query.Where(p => p.AssistPhone.Contains(input.AssistPhone));

            //镇
            if (input.TownID != 0)
                query = query.Where(p => p.TownID == input.TownID);

            //区
            if (input.AreaID != 0)
                query = query.Where(p => p.AreaID == input.AreaID);

            //村庄
            if (input.VillageID != 0)
                query = query.Where(p => p.VillageID == input.VillageID);

            #endregion

            var gridPersonCount = await query.CountAsync();

            var gridPersons = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();

            var areaList = _areaRepository.GetAll();
            var personTypeList = _personTypeRepository.GetAll();
            return new PagedResultDto<GridPersonListDto>(gridPersonCount,
                gridPersons.Select(item =>
                {
                    var dto = item.MapTo<GridPersonListDto>();
                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var personTypeModel = personTypeList.Where(p => p.Id == dto.PersonTypeID).FirstOrDefault();
                    if (personTypeModel != null)
                        dto.PersonTypeTitle = personTypeModel.Name;
                    return dto;
                }).ToList());
        }

        /// <summary>
        /// 通过Id获取网格基本信息信息进行编辑或修改 
        /// </summary>
        public async Task<GetGridPersonForEditOutput> GetGridPersonForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetGridPersonForEditOutput();

            GridPersonEditDto gridPersonEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _gridPersonRepository.GetAsync(input.Id.Value);
                gridPersonEditDto = entity.MapTo<GridPersonEditDto>();
            }
            else
            {
                gridPersonEditDto = new GridPersonEditDto();
            }

            output.GridPerson = gridPersonEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取网格基本信息ListDto信息
        /// </summary>
        public async Task<GridPersonListDto> GetGridPersonByIdAsync(EntityDto<long> input)
        {
            var entity = await _gridPersonRepository.GetAsync(input.Id);

            return entity.MapTo<GridPersonListDto>();
        }







        /// <summary>
        /// 新增或更改网格基本信息
        /// </summary>
        public async Task CreateOrUpdateGridPersonAsync(CreateOrUpdateGridPersonInput input)
        {
            if (input.GridPersonEditDto.Id.HasValue)
            {
                await UpdateGridPersonAsync(input.GridPersonEditDto);
            }
            else
            {
                await CreateGridPersonAsync(input.GridPersonEditDto);
            }
        }

        /// <summary>
        /// 新增网格基本信息
        /// </summary>
        [AbpAuthorize(GridPersonAppPermissions.GridPerson_CreateGridPerson)]
        public virtual async Task<GridPersonEditDto> CreateGridPersonAsync(GridPersonEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<GridPerson>();

            entity = await _gridPersonRepository.InsertAsync(entity);
            return entity.MapTo<GridPersonEditDto>();
        }

        /// <summary>
        /// 编辑网格基本信息
        /// </summary>
        [AbpAuthorize(GridPersonAppPermissions.GridPerson_EditGridPerson)]
        public virtual async Task UpdateGridPersonAsync(GridPersonEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _gridPersonRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _gridPersonRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除网格基本信息
        /// </summary>
        [AbpAuthorize(GridPersonAppPermissions.GridPerson_DeleteGridPerson)]
        public async Task DeleteGridPersonAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _gridPersonRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除网格基本信息
        /// </summary>
        [AbpAuthorize(GridPersonAppPermissions.GridPerson_DeleteGridPerson)]
        public async Task BatchDeleteGridPersonAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _gridPersonRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 网格基本信息的Excel导出功能

        public async Task<FileDto> GetGridPersonToExcel()
        {
            var entities = await _gridPersonRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<GridPersonListDto>>();

            var fileDto = _gridPersonListExcelExporter.ExportGridPersonToFile(dtos);



            return fileDto;
        }

        #endregion

    }
}
